package com.geng.connect;

import com.geng.dto.ProviderService;
import com.geng.invoker.NettyChannelFactory;

import java.lang.reflect.Method;
import java.net.InetSocketAddress;

public class DCConnect implements IConnectStrategy {
    /**
     * 需要调用的服务的接口
     */
    private Class<?> targetInterface;
    /**
     * socket
     */
    private ProviderService providerService;


    public DCConnect(Builder builder) {
        this.targetInterface = builder.targetInterface;
        this.providerService = builder.providerService;
    }

    @Override
    public ProviderService creatProvider(Method method) {
        ProviderService newProvider = this.providerService;
        newProvider.setServiceMethod(method);
        newProvider.setServiceItf(targetInterface);
        return newProvider;
    }

    @Override
    public void registeChannel(ChannelPara para) {
        String socket = para.getSocket();
        String[] socket1 = socket.split(":");
        String ip = socket1[0];
        int port = Integer.valueOf(socket1[1]);
        InetSocketAddress socketAddress  = new InetSocketAddress(ip, port);
        providerService.setServerIp(ip);
        providerService.setServerPort(port);
        NettyChannelFactory.channelFactoryInstance().initChannelPoolFactory(socketAddress);
    }

    public static class Builder{
        /**
         * 需要调用的服务的接口
         */
        private Class<?> targetInterface;
        /**
         * socket
         */
        private ProviderService providerService;


        public Builder(){

        }

        public Builder targetInterface(Class<?> targetInterface){
            this.targetInterface = targetInterface;
            return this;
        }

         public Builder providerService(ProviderService providerService){
             this.providerService = providerService;
             return this;
         }

         public DCConnect build(){
            return new DCConnect(this);
         }
    }
}
